package com.ming_za.odupdaterserver.core.sqlite.type_handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ming_za.odupdaterserver.core.utils.JsonUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

public abstract class JsonTypeHandler<T> extends BaseTypeHandler<T> {

    protected final JsonUtils jsonUtils;

    public JsonTypeHandler(JsonUtils jsonUtils) {
        this.jsonUtils = jsonUtils;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, jsonUtils.toJson(parameter));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String r = rs.getString(columnName);
        if (r != null){
            return toObj(r);
        };
        return null;
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String r = rs.getString(columnIndex);
        if (r != null){
            return toObj(r);
        };
        return null;
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String r = cs.getNString(columnIndex);
        if (r != null){
            return toObj(r);
        };
        return null;
    }

    public abstract T toObj(String json);

}
